package com.xbenben.project.common.init;

import com.google.common.collect.Maps;
import com.xbenben.project.common.utils.SpringContextUtils;
import com.xbenben.project.demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

/**
 * @author xbenbenx
 * Date:2022/11/21 23:27
 **/
@Component
public class Processor implements InitData {
    private static final String TRANSFORMABLE_CONFIG_FILE_PATH = "META-INF/crm/crm-message-transformer.properties";
    private static final String PROCESSOR_CONFIG_FILE_PATH = "META-INF/crm/crm-message-processor.properties";

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 通过 配置文件 获取 策率 bean
     */
    private static <T> Map<String, T> buildBeanMappingInfo(String configPath, Class<T> clazz) throws IOException {
        // 1.获取配置参数
        Properties configProperties = getConfigProperties(configPath);
        if (configProperties.isEmpty()) {
            return null;
        }
        Map<String, T> mappingInfo = Maps.newHashMapWithExpectedSize(configProperties.size());
        for (String mappingKey : configProperties.stringPropertyNames()) {
            // 2. 根据配置参数获取对应的Bean
            String beanName = configProperties.getProperty(mappingKey);
            T mappingBean = SpringContextUtils.getApplicationContext().getBean(beanName, clazz);
            // 3. 设置映射关系
            mappingInfo.put(mappingKey, mappingBean);
        }
        return mappingInfo;
    }

    /**
     * 获取 实体
     */
    private static Properties getConfigProperties(String configPath) throws IOException {
        return PropertiesLoaderUtils.loadAllProperties(configPath, Processor.class.getClassLoader());
    }

    /**
     * 初始化 数据 策略类 map
     */
    @Override
    public void loadData() {

        String[] names = applicationContext.getBeanNamesForType(DemoService.class);
        for (String component : names) {
            System.out.println("实现类：" + component);
        }
        System.out.println("初始化User 数据");

    }
}
